package com.service;
import com.dao.AsUserDao;
import com.entity.AsUser;
import com.utils.JsonUtil;
import com.utils.Pager;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

@Service
public class AsUserService
{
    @Resource
    private AsUserDao asUserDao;

    //使用用户名和密码查询 返回1个用户
    public AsUser returnOneUserByNameAndPass( AsUser user )
    {
        return asUserDao.getOneUserByNameAndPass( user.getUserName() , user.getUserPassword() );
    }

    //返回所有可用用户的用户名和对应角色名称json数据
    public String returnUsersAndRoleNameJsonStr()
    {
        ArrayList<Map<String,Object>> userList = asUserDao.getAllAvaliableUserAndRoleName();
        String jsonStr = JsonUtil.toJsonStr( userList );
        //System.out.println( jsonStr );

        return jsonStr;
    }

    //更新一位用户的密码
    public Integer updateUserPassword( AsUser user )
    {
        return  asUserDao.updateOneUser( user );
    }

    //返回用户管理页面显示数据
    public String returnUserManagePageJsonStr( Integer page , Integer size )
    {
        Integer total = asUserDao.getUserCountByCondition();
        Integer index = ( page - 1 ) * size;
        ArrayList<Map<String,Object>> userList = asUserDao.getAllUserAndRoleNameInfo( index , size );
        Pager<Map<String,Object>> pager = new Pager<>();
        pager.setTotal( total );
        pager.setRows( userList );
        String jsonStr = JsonUtil.toJsonStrWithDateTime( pager );
        //System.out.println( ">>>>>>>>>>" + jsonStr );

        return jsonStr;
    }

    //根据id删除指定用户
    public String delUser( Integer id )
    {
        Integer resultCode = asUserDao.delOneUser( id );

        return JsonUtil.successOrNotJsonStr( resultCode );
    }

    //添加一位用户
    public String addUser( AsUser user , String currentUserName )
    {
        //密码不存在或为空则设置默认密码
        if( user.getUserPassword() == null || "".equals( user.getUserPassword() ) )
        {
            user.setUserPassword( "123456" );
        }
        Date now = new Date();
        user.setCreationTime( now );
        user.setLastUpdateTime( now );
        user.setCreatedBy( currentUserName );
        Integer resultCode = asUserDao.addOneUser( user );

        return JsonUtil.successOrNotJsonStr( resultCode );
    }

    //根据id返回1位用户json数据
    public String returnOneUserJsonStr( Integer id )
    {
        AsUser user = asUserDao.getOneUserById( id );

        return JsonUtil.toJsonStr( user );
    }

    //更新1位用户
    public String updateOneUser( AsUser user )
    {
        user.setLastUpdateTime( new Date() );
        Integer resultCode = asUserDao.updateOneUser( user );

        return JsonUtil.successOrNotJsonStr( resultCode );
    }

}
